package com.ems.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ems.entity.MerchantEntity;
import com.ems.mapper.MerchantMapper;
import com.ems.service.IMerchantService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ems.util.SnowflakeIdWorker;
import com.ems.util.StateEnum;
import com.ems.util.StateException;
import com.ems.vo.MerchantVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 商户/部门表 服务实现类
 * </p>
 *
 * @author WuZH
 * @since 2023-10-24
 */
@Service
public class MerchantServiceImpl extends ServiceImpl<MerchantMapper, MerchantEntity> implements IMerchantService {

    @Resource
    private MerchantMapper merchantMapper;

    @Override
    public List<MerchantVo> queryList ( MerchantVo merchantVo ) {
        merchantVo.setPage ( ( merchantVo.getPage () - 1 ) * merchantVo.getLimit () );
        List<MerchantVo> merchantVos = merchantMapper.queryList ( merchantVo );
        return merchantVos;
    }

    @Override
    public Integer queryCount ( MerchantVo merchantVo ) {
        Integer count = merchantMapper.queryCount ( merchantVo );
        return count;
    }

    @Override
    public MerchantVo querySingle ( MerchantVo merchantVo ) {
        QueryWrapper<MerchantEntity> queryWrapper = new QueryWrapper<> ();
        if ( StringUtils.isNotBlank ( merchantVo.getId () ) ) {
            queryWrapper.eq ( "id", merchantVo.getId () );
        }
        MerchantEntity merchantEntity = baseMapper.selectOne ( queryWrapper );
        BeanUtils.copyProperties ( merchantEntity, merchantVo );
        return merchantVo;
    }

    @Override
    public MerchantVo saveSingle ( MerchantVo merchantVo ) {
        if ( merchantVo == null ) {
            throw new StateException ( StateEnum.REQUEST_PARAM_EXCE );
        }
        MerchantEntity merchantEntity = new MerchantEntity ();
        BeanUtils.copyProperties ( merchantVo, merchantEntity );
        merchantEntity.setId ( SnowflakeIdWorker.getInstance ().nextStringId () );
        merchantEntity.setCreateTime ( new Date () );
        int insert = baseMapper.insert ( merchantEntity );
        if ( insert == 0 ) {
            throw new StateException ( StateEnum.INSERT_EXCE );
        }
        return merchantVo;
    }

    @Override
    public MerchantVo updateSingle ( MerchantVo merchantVo ) {
        return null;
    }
}
